<template>
  <div class="scroll-container" ref="container" @scroll="handleScroll">
    <div class="phantom" :style="{ height: totalHeight + 'px' }"></div>
    <div class="content" :style="{ transform: `translateY(${offset}px)` }">
      <div
        v-for="item in visibleData"
        :key="item.id"
        class="item"
        :style="{ height: itemHeight + 'px' }"
      >
        {{ item.index + 1 + '------' + item.date + item.name + item.address }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const props = defineProps({
  data: { type: Array, required: true },
  itemHeight: { type: Number, default: 50 }
})

const container = ref(null)
const scrollTop = ref(0)
const clientHeight = ref(0)

const totalHeight = computed(() => props.data.length * props.itemHeight)
const startIndex = computed(() => Math.floor(scrollTop.value / props.itemHeight))
const endIndex = computed(() =>
  Math.min(startIndex.value + Math.ceil(clientHeight.value / props.itemHeight), props.data.length)
)
const offset = computed(() => startIndex.value * props.itemHeight)
const visibleData = computed(() => props.data.slice(startIndex.value, endIndex.value))

function handleScroll() {
  scrollTop.value = container.value.scrollTop
}

onMounted(() => {
  clientHeight.value = container.value.clientHeight
})
</script>

<style scoped>
.scroll-container {
  position: relative;
  height: 500px;
  overflow: auto;
}
.phantom {
  position: absolute;
  width: 100%;
}
.content {
  position: absolute;
  width: 100%;
}
.item {
  display: flex;
  align-items: center;
  padding: 0 16px;
  border-bottom: 1px solid #eee;
}
</style>
